import os
import subprocess
import xml.etree.ElementTree as ET
import argparse

def find_tz_exe_path():
    # Parse the XML file to locate <Exec Command> with tz.exe or tz path
    tree = ET.parse("Directory.Build.targets")
    root = tree.getroot()
    tz_filename = "tz.exe" if os.name == "nt" else "tz"

    for exec_command in root.findall(".//Exec"):
        command = exec_command.get("Command")
        if command and tz_filename in command:
            tz_path = command.split(tz_filename)[0].strip() + tz_filename
            return os.path.abspath(tz_path)
    return None

def find_tizen_script_path(tz_exe_path, user_provided_path=None):
    # Use user-provided path if available, otherwise attempt to derive path
    if user_provided_path and os.path.exists(user_provided_path):
        return user_provided_path

    base_dir = os.path.dirname(os.path.dirname(tz_exe_path))
    tizen_script = "tizen.bat" if os.name == "nt" else "tizen.sh"
    tizen_script_path = os.path.join(base_dir, "ide", "bin", tizen_script)

    if os.path.exists(tizen_script_path):
        return tizen_script_path

    return None

def find_tpk_file():
    # Find .tpk file in the ./LightsyncService/ directory
    tpk_directory = "./LightsyncService"
    for file in os.listdir(tpk_directory):
        if file.endswith(".tpk"):
            return os.path.join(tpk_directory, file)
    return None

def find_wgt_file():
    # Find .wgt file in the current directory
    for file in os.listdir("."):
        if file.endswith(".wgt"):
            return file
    return None

def main(profile_name, tizen_script_path=None):
    tz_exe_path = find_tz_exe_path()
    if not tz_exe_path:
        print("tz path not found")
        return

    tizen_script_path = find_tizen_script_path(tz_exe_path, tizen_script_path)
    if not tizen_script_path:
        print("tizen script file not found. Please provide the path as an argument.")
        return

    tpk_file = find_tpk_file()
    wgt_file = find_wgt_file()

    if not tpk_file or not wgt_file:
        print(".tpk or .wgt file not found")
        return

    command = [
        tizen_script_path, "package", "-t", "wgt",
        "-s", profile_name,
        "-r", tpk_file,
        "--", f"./{wgt_file}"
    ]

    try:
        subprocess.run(command, check=True)
        print("Command executed successfully")
    except subprocess.CalledProcessError as e:
        print("Command execution failed:", e)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Package a Tizen application.")
    parser.add_argument("profile_name", help="The name of the signing profile.")
    parser.add_argument(
        "--tizen-script-path",
        help="Optional path to the Tizen script (tizen.bat or tizen.sh). "
             "If not provided, the script will attempt to locate it automatically.",
        default=None
    )

    args = parser.parse_args()
    main(args.profile_name, args.tizen_script_path)
